var util = require('../../utils/util.js');
var utilMd5 = require('../../utils/md5.js');
var base64 = require('../../utils/Base64.js');
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    userinfo: {},
    uid: 0,
    token: 0,
    openid: 0,
    shareImgUrl: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.showLoading({
      title: '正在生成海报。。。',
    });
    var that = this;
    var imgUrl = base64.decode(options.imgUrl);
    if (imgUrl.indexOf('http:') >= 0) {
      imgUrl = imgUrl.replace(/^http:/, 'https:');
    }
    console.log("imgurl: ", imgUrl);
    this.setData({
      shareImgUrl: imgUrl
    });
    
    app.LoginUserInfo(function (res) {
      if (res && res != -1) {
      that.setData({
        uid: res.uid,
        token: res.token,
        openid: res.wxsmall_openid
      });
      }
    });

    app.GetUserInfo(that.data.uid, function (res) {
      that.setData({
        userinfo: res,
        haibaoUrl: res.avatar
      });
    });
  },

  loadImageFinish: function(e){
    console.log("loadImageFinish:", e)
    wx.hideLoading();
  },

  saveImage: function(e){
    console.log("formid: ", e.detail.formId);
    var that = this;
    app.saveFormId(e.detail.formId);//保存fromId

    var imgUrl = that.data.shareImgUrl;
    if (imgUrl.indexOf('http:') >= 0){
      imgUrl = imgUrl.replace(/^http:/, 'https:');
    }
    console.log("imgurl2: ", imgUrl);

    wx.downloadFile({
      url: imgUrl,
      type: 'image',
      success: function (res) {
        wx.saveImageToPhotosAlbum({
          filePath: res.tempFilePath,
          success: function (res) {
            wx.showToast({
              // title: '海报已保存' + res.errMsg,
              title: '海报已保存',
              icon: 'success'
            })
          },
          fail: function (e) {
            console.log(e);
            wx.showToast({
              title: '保存失败',
              icon: 'fail'
            });
          }
        })
      },
      fail: function (e) {
        console.log(e);
        wx.showToast({
          title: '下载图片失败' + JSON.stringify(e),
          icon: 'fail'
        });
      }
    });
  },
})